package lesson24;

import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class MyWaitQueue {

    private int max;

    private LinkedList<Integer> queue;

    public AtomicInteger count = new AtomicInteger();

    public MyWaitQueue(int max){
        this.max = max;
        this.queue = new LinkedList();
    }

    public static void main(String[] args) {

        ExecutorService executorService = Executors.newFixedThreadPool(10);

        MyWaitQueue myWaitQueue = new MyWaitQueue(10);

        executorService.execute(() -> {
            while (true){
                myWaitQueue.put();
            }
        });


        executorService.execute(() -> {
            while (true){
                myWaitQueue.take();
            }
        });
    }

    public synchronized  void put(){
        while (queue.size() == max){
            try {
                System.out.println("queue size : "+ queue.size() + " 队列已满。。。");
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("queue put : " + count.getAndIncrement());
        queue.add(count.get());
        this.notifyAll();
    }

    public synchronized void take(){
        while (queue.size() == 0){
            try {
                System.out.println("queue size : "+ queue.size() + " 队列已空。。。");
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("queue take : " + queue.remove());
        this.notifyAll();
    }
}
